{% extends 'base.html' %}

{% block title %}扫描二维码{% endblock %}

{% block extra_css %}
<style>
    .scan-container {
        background: white;
        border-radius: 15px;
        padding: 30px;
        box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        text-align: center;
        margin: 20px 0;
    }
    
    .camera-container {
        position: relative;
        max-width: 400px;
        margin: 0 auto;
        border-radius: 10px;
        overflow: hidden;
        background: #f8f9fa;
    }
    
    #video {
        width: 100%;
        height: auto;
        display: block;
    }
    
    .scan-overlay {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 200px;
        height: 200px;
        border: 2px solid #007bff;
        border-radius: 10px;
        box-shadow: 0 0 0 9999px rgba(0,0,0,0.5);
    }
    
    .scan-corners {
        position: absolute;
        width: 20px;
        height: 20px;
        border: 3px solid #007bff;
    }
    
    .scan-corners.top-left {
        top: -2px;
        left: -2px;
        border-right: none;
        border-bottom: none;
    }
    
    .scan-corners.top-right {
        top: -2px;
        right: -2px;
        border-left: none;
        border-bottom: none;
    }
    
    .scan-corners.bottom-left {
        bottom: -2px;
        left: -2px;
        border-right: none;
        border-top: none;
    }
    
    .scan-corners.bottom-right {
        bottom: -2px;
        right: -2px;
        border-left: none;
        border-top: none;
    }
    
    .manual-input-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 15px;
        padding: 25px;
        margin: 20px 0;
    }
    
    .btn-custom {
        border-radius: 25px;
        padding: 12px 30px;
        font-weight: 500;
        margin: 5px;
        transition: all 0.3s ease;
    }
    
    .btn-custom:hover {
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.2);
    }
    
    .status-message {
        margin: 15px 0;
        padding: 10px;
        border-radius: 8px;
        font-weight: 500;
    }
    
    .status-success {
        background: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
    }
    
    .status-error {
        background: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
    }
    
    .status-info {
        background: #d1ecf1;
        color: #0c5460;
        border: 1px solid #bee5eb;
    }
</style>
{% endblock %}

{% block content %}
<div class="container">
    <!-- 面包屑导航 -->
    <nav aria-label="breadcrumb" class="mb-4">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="{% url 'assets:index' %}">首页</a></li>
            <li class="breadcrumb-item"><a href="{% url 'assets:asset_list' %}">资产管理</a></li>
            <li class="breadcrumb-item active">扫描二维码</li>
        </ol>
    </nav>

    <div class="row">
        <div class="col-md-8">
            <!-- 扫描区域 -->
            <div class="scan-container">
                <h4 class="mb-4">
                    <i class="fas fa-camera text-primary me-2"></i>
                    扫描资产二维码
                </h4>
                
                <!-- 摄像头容器 -->
                <div class="camera-container mb-4">
                    <video id="video" autoplay muted playsinline></video>
                    <div class="scan-overlay">
                        <div class="scan-corners top-left"></div>
                        <div class="scan-corners top-right"></div>
                        <div class="scan-corners bottom-left"></div>
                        <div class="scan-corners bottom-right"></div>
                    </div>
                </div>
                
                <!-- 状态消息 -->
                <div id="status-message" class="status-message status-info">
                    <i class="fas fa-info-circle me-2"></i>
                    请将二维码对准扫描框进行扫描
                </div>
                
                <!-- 控制按钮 -->
                <div class="mb-4">
                    <button id="start-scan" class="btn btn-success btn-custom">
                        <i class="fas fa-play me-2"></i>开始扫描
                    </button>
                    <button id="stop-scan" class="btn btn-danger btn-custom" style="display: none;">
                        <i class="fas fa-stop me-2"></i>停止扫描
                    </button>
                    <button id="switch-camera" class="btn btn-info btn-custom" style="display: none;">
                        <i class="fas fa-sync-alt me-2"></i>切换摄像头
                    </button>
                </div>
            </div>
        </div>
        
        <div class="col-md-4">
            <!-- 手动输入 -->
            <div class="manual-input-card">
                <h5 class="mb-4">
                    <i class="fas fa-keyboard me-2"></i>
                    手动输入
                </h5>
                
                <form method="post">
                    {% csrf_token %}
                    <div class="mb-3">
                        <label for="qr_data" class="form-label">二维码数据：</label>
                        <textarea class="form-control" id="qr_data" name="qr_data" rows="4" 
                                placeholder="请粘贴或输入二维码内容..."></textarea>
                    </div>
                    <button type="submit" class="btn btn-light btn-custom w-100">
                        <i class="fas fa-search me-2"></i>查询资产
                    </button>
                </form>
            </div>
            
            <!-- 使用说明 -->
            <div class="card">
                <div class="card-body">
                    <h6 class="card-title">
                        <i class="fas fa-question-circle me-2"></i>使用说明
                    </h6>
                    <ul class="list-unstyled mb-0">
                        <li class="mb-2">
                            <i class="fas fa-check text-success me-2"></i>
                            点击"开始扫描"启用摄像头
                        </li>
                        <li class="mb-2">
                            <i class="fas fa-check text-success me-2"></i>
                            将二维码对准扫描框
                        </li>
                        <li class="mb-2">
                            <i class="fas fa-check text-success me-2"></i>
                            系统会自动识别并跳转
                        </li>
                        <li class="mb-2">
                            <i class="fas fa-check text-success me-2"></i>
                            也可手动输入二维码内容
                        </li>
                    </ul>
                </div>
            </div>
            
            <!-- 快捷链接 -->
            <div class="card mt-3">
                <div class="card-body">
                    <h6 class="card-title">
                        <i class="fas fa-link me-2"></i>快捷链接
                    </h6>
                    <div class="d-grid gap-2">
                        <a href="{% url 'assets:asset_list' %}" class="btn btn-outline-primary btn-sm">
                            <i class="fas fa-list me-2"></i>资产列表
                        </a>
                        <a href="{% url 'assets:asset_batch_print_labels' %}" class="btn btn-outline-success btn-sm">
                            <i class="fas fa-print me-2"></i>批量打印标签
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<!-- 引入二维码扫描库 -->
<script src="https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const video = document.getElementById('video');
    const startBtn = document.getElementById('start-scan');
    const stopBtn = document.getElementById('stop-scan');
    const switchBtn = document.getElementById('switch-camera');
    const statusMessage = document.getElementById('status-message');
    const qrDataInput = document.getElementById('qr_data');
    
    let stream = null;
    let scanning = false;
    let currentCamera = 0;
    let cameras = [];
    
    // 获取可用摄像头
    async function getCameras() {
        try {
            const devices = await navigator.mediaDevices.enumerateDevices();
            cameras = devices.filter(device => device.kind === 'videoinput');
            
            if (cameras.length > 1) {
                switchBtn.style.display = 'inline-block';
            }
        } catch (error) {
            console.error('获取摄像头列表失败:', error);
        }
    }
    
    // 启动摄像头
    async function startCamera() {
        try {
            const constraints = {
                video: {
                    facingMode: currentCamera === 0 ? 'environment' : 'user',
                    width: { ideal: 400 },
                    height: { ideal: 300 }
                }
            };
            
            if (cameras.length > 0) {
                constraints.video.deviceId = cameras[currentCamera].deviceId;
            }
            
            stream = await navigator.mediaDevices.getUserMedia(constraints);
            video.srcObject = stream;
            
            updateStatus('摄像头已启动，请将二维码对准扫描框', 'info');
            
            startBtn.style.display = 'none';
            stopBtn.style.display = 'inline-block';
            
            // 开始扫描
            scanning = true;
            scanQRCode();
            
        } catch (error) {
            console.error('启动摄像头失败:', error);
            updateStatus('无法访问摄像头，请检查权限设置', 'error');
        }
    }
    
    // 停止摄像头
    function stopCamera() {
        if (stream) {
            stream.getTracks().forEach(track => track.stop());
            stream = null;
        }
        
        scanning = false;
        video.srcObject = null;
        
        startBtn.style.display = 'inline-block';
        stopBtn.style.display = 'none';
        
        updateStatus('扫描已停止', 'info');
    }
    
    // 切换摄像头
    function switchCamera() {
        if (cameras.length > 1) {
            currentCamera = (currentCamera + 1) % cameras.length;
            if (scanning) {
                stopCamera();
                setTimeout(startCamera, 100);
            }
        }
    }
    
    // 扫描二维码
    function scanQRCode() {
        if (!scanning) return;
        
        const canvas = document.createElement('canvas');
        const context = canvas.getContext('2d');
        
        if (video.readyState === video.HAVE_ENOUGH_DATA) {
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            context.drawImage(video, 0, 0, canvas.width, canvas.height);
            
            const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
            
            if (typeof jsQR !== 'undefined') {
                const code = jsQR(imageData.data, imageData.width, imageData.height);
                
                if (code) {
                    updateStatus('二维码识别成功！正在跳转...', 'success');
                    
                    // 填充到手动输入框
                    qrDataInput.value = code.data;
                    
                    // 自动提交表单
                    setTimeout(() => {
                        document.querySelector('form').submit();
                    }, 1000);
                    
                    return;
                }
            }
        }
        
        // 继续扫描
        requestAnimationFrame(scanQRCode);
    }
    
    // 更新状态消息
    function updateStatus(message, type) {
        statusMessage.textContent = message;
        statusMessage.className = `status-message status-${type}`;
        
        // 添加图标
        const icon = type === 'success' ? 'check-circle' : 
                    type === 'error' ? 'exclamation-triangle' : 'info-circle';
        statusMessage.innerHTML = `<i class="fas fa-${icon} me-2"></i>${message}`;
    }
    
    // 事件监听
    startBtn.addEventListener('click', startCamera);
    stopBtn.addEventListener('click', stopCamera);
    switchBtn.addEventListener('click', switchCamera);
    
    // 初始化
    getCameras();
    
    // 页面卸载时停止摄像头
    window.addEventListener('beforeunload', stopCamera);
});
</script>
{% endblock %}
